package com.example.fun.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.fun.R;
import com.example.fun.bean.LoginBean;
import com.example.fun.bean.RegisterBean;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private static final String TAG = "RegisterActivity";
    private Button btnRegistered;
    private TextView tvGoLogin;
    private EditText edName;
    private EditText edPwd;
    private EditText edRePwd;

    private OkHttpClient client = new OkHttpClient();
    private Intent intent = null;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
//                String resultStr  = (String) msg.obj;
//                Log.i("获取返回的信息：", resultStr );
//                final RegisterBean registerBean = new Gson().fromJson(resultStr , RegisterBean.class);
//                final RegisterBean registerBean = new RegisterBean();
                RegisterBean registerBean = new Gson().fromJson(((String) msg.obj), RegisterBean.class);
                int resultCode = registerBean.getErrorCode();
                String resultMsg = registerBean.getErrorMsg();
                Log.i("获取返回的信息：", String.valueOf(resultMsg));
                if (resultCode == 0) {
                    Toast.makeText(RegisterActivity.this, "注册成功：" + resultCode, Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(RegisterActivity.this, "注册失败：" + resultMsg, Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);

        initView();

    }

    private void initView() {
        btnRegistered = (Button) findViewById(R.id.btn_registered);
        tvGoLogin = (TextView) findViewById(R.id.tv_goLogin);
        edName = (EditText) findViewById(R.id.registered_name);
        edPwd = (EditText) findViewById(R.id.registered_pwd);
        edRePwd = (EditText) findViewById(R.id.registered_rePwd);

        btnRegistered.setOnClickListener(this);
        tvGoLogin.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.btn_registered:
                Register();
                break;
            case R.id.tv_goLogin:
                intent = new Intent(getApplicationContext(), LoginActivity.class);
                startActivity(intent);
                finish();
            default:
                break;
        }
    }

    private void Register() {
        String name = edName.getText().toString().trim();
        if(TextUtils.isEmpty(name)){
            Toast.makeText(this, "请输入用户名！", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = edPwd.getText().toString().trim();
        if(TextUtils.isEmpty(password)){
            Toast.makeText(this, "密码不能为空！", Toast.LENGTH_SHORT).show();
            return;
        }

        String rePassword = edRePwd.getText().toString().trim();
        if(TextUtils.isEmpty(rePassword)){
            Toast.makeText(this, "请确认密码！", Toast.LENGTH_SHORT).show();
            return;
        }

        if(!rePassword.equals(password)){
            Toast.makeText(this, "两次密码不一致！", Toast.LENGTH_SHORT).show();
        }else {
//            final JSONObject jsonObject = new JSONObject();
//            try {
//                jsonObject.put("username", name);
//                jsonObject.put("password", password);
//                jsonObject.put("repassword", rePassword);
//            }catch (JSONException e){
//                e.printStackTrace();
//            }
//
//            MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
//            final RequestBody requestBody = RequestBody.create(mediaType, jsonObject.toString());
            FormBody formBody = new FormBody.Builder()
                    .add("username", name)
                    .add("password", password)
                    .add("repassword", rePassword)
                    .build();
            Request request = new Request.Builder()
                    .post(formBody)
                    .url("https://www.wanandroid.com/user/register")
                    .build();
            OkHttpClient client = new OkHttpClient();
            Call call = client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    Log.d(TAG, "onFailure: " + e.getMessage());
                }

                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                    final String registerBody = response.body().string();
                    Log.d(TAG, "success: " + registerBody);
                    Message msg = new Message();
                    msg.obj = registerBody;
                    handler.sendMessage(msg);
                    if(registerBody != null){
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this, "注册成功！", Toast.LENGTH_SHORT).show();
//                                btnRegistered.setOnClickListener(new View.OnClickListener() {
//                                    @Override
//                                    public void onClick(View v) {
//                                        Intent intent = new Intent();
//                                        intent.setClass(RegisterActivity.this, LoginActivity.class);
//                                        startActivity(intent);
//                                    }
//                                });
                            }
                        });

                    }else {
                        Gson gson = new Gson();
                        RegisterBean registerBean = gson.fromJson(registerBody, RegisterBean.class);
                        String registerMsg = registerBean.getErrorMsg();
                        Log.d(TAG, "registerMsg: " + registerMsg);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(RegisterActivity.this, "registerMsg: " + registerMsg, Toast.LENGTH_LONG).show();
                            }
                        });

                    }
                }
            });
        }

    }

}
